<?php

namespace App\Http\Controllers\Client\Shop\Explore;

use App\Http\Controllers\ClientController;
use App\Models\Common\Common;
use App\Models\Tools\Data;
use App\Models\Work;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ExploreGiveUpController extends ClientController
{

    public function index()
    {

        $all = $this->all;
        $work_id = $all['work_id'];
        $remark = $all['remark'];

        try {
            DB::beginTransaction();
            // 查询工单信息
            // 查询订单、工单、余量信息并锁表
            $work = Work::exploreWorkAndX($work_id);
            $order = Work::exploreOrderAndX($work['eo_id']);
            $remaining = Work::exploreRemainingAndX($order['we_id'], $order['channel_id']);
            // 判断所有者和状态
            if ($work['receiver_we_id'] !== $this->we_id){
                return $this->setReturnJson(-1,'您不是这个任务的所有者');
            }
            if (!in_array($work['status'],[Data::DATA_DB_EXPLORE_WORK_STATUS_INIT, Data::DATA_DB_EXPLORE_WORK_STATUS_REFUSE])) {
                return $this->setReturnJson(-1,'当前工单状态不允许放弃');
            }

            // 放弃这个工单
            DB::table('explore_work')->where('work_id','=',$work_id)->update([
                'status'=>Data::DATA_DB_EXPLORE_WORK_STATUS_ERROR,
                'error_reason'=>Data::DATA_DB_EXPLORE_WORK_ERROR_REASON_GIVE_UP,
                'reason_detail' => $remark,
            ]);

            // 记录工单日志
            DB::table('explore_work_log')->insert([
                'work_id'=>$work_id,
                'action'=>Data::DATA_DB_EXPLORE_WORK_ACTION_GIVE_UP,
                'we_id'=>$this->we_id,
                'remark'=>'用户【'.$this->nickname.'】放弃：'.$remark,
            ]);

            // 修改订单状态
            Work::workCancelToOrder($order);
            // 修改发单者剩余数量并记录日志
            Work::workCancelToRemaining($remaining);

            DB::commit();
        } catch (\Exception $e) {
            Log::error(ExploreGiveUpController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            DB::rollBack();
            return $this->setReturnJson(-1,'放弃失败');
        }

        //  发送验收拒回微信通知（发送给商家）
        $data = [
            'first' => '您有一个探店活动已被达人放弃。',
            'keyword1' => '达人探店',
            'keyword2' => '达人【'.$this->nickname.'】',
            'keyword3' => date('Y-m-d H:i:s'),
            'keyword4' => $remark,
            'remark' => '探店次数余量已退还到您的账户，您可以再次申请探店，点击查看详情。',
        ];
        //发送通知
        $openid = DB::table('lottery_users')->where('we_id','=',$work['apply_we_id'])->value('openid');
        Common::sendLaifeiMessage($openid,'work_cancel',$data,'/history?tab=1');

        return $this->setReturnJson(0,'success');

    }

}
